import { login,getCode,register,getInfo,logout  } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/token'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
  }
}
const state = getDefaultState()


const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    let result = await login(userInfo);
    if (result.code === 200) {
      commit('SET_TOKEN', result.data.token)
      setToken(result.data.token)
      return result
    }
    else {
      return result
    }
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await getInfo();
    if (result.code == 200) {
      const { data } = result
      if (!data) {
        return reject('Verification failed, please Login again.')
      }
      commit('SET_NAME', data.nickname)
      commit('SET_AVATAR', data.avatar)
      commit('SET_USERINFO', data)
      return 'ok'
    }
    else {
      return Promise.reject(new Error('faile'))
    }

  },

  // 用户退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 清除token
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  //获取验证码
  async getCode(context, username) {
    try {
      let result = await getCode(username)
      return result;
    } catch (error) {
      Promise.reject(new Error('faile'))
    }
  },
  //注册
  async register(context,registerInfo){
    try {
      let result = await register(registerInfo)
      return result;
    } catch (error) {
      return Promise.reject(new Error('faile'))
    }
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

